#include "pch.h"
#include "include/threads.h"
#include "include/LogInit.h"
#ifdef WIN32
#include <windows.h>          // for HANDLE
#include <process.h>          // for _beginthread()	
#else
// linux include
#include <errno.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <sys/wait.h>
#include <unistd.h>
#include <arpa/inet.h>
// #include <openssl/ssl.h>
// #include <openssl/err.h>
#include <fcntl.h>
#include <sys/epoll.h>
#include <sys/time.h>
#include <sys/resource.h>
#include <pthread.h>	
#endif


ThreadFunSignature(threadFunc)
{
	Thread* tptd = static_cast<Thread*>(param);

#ifdef WIN32
#else			
	pthread_detach(pthread_self());
#endif

	//tptd->onStart();

	//if(!tptd->m_isCancel)
	{
		//tptd->onProcessTaskStart(task);
		LogInfo("tptd->Run  this:[%p]", tptd);
		tptd->Run();
		//tptd->onProcessTaskEnd(task);
	}

#ifdef WIN32
	return 0;
#else	
	pthread_exit(NULL);
	//return NULL;
#endif		
}


//-------------------------------------------------------------------------------------
Thread::Thread():m_threadID(0), m_task(this), m_isCancel(true)
{
}
Thread::Thread(Runable* task) : m_threadID(0), m_task(task), m_isCancel(true)
{

}
Thread::~Thread()
{

}

void Thread::Run()
{
	if (m_task)
	{
		m_task->Run();
	}
}
void Thread::Start()
{
	this->m_isCancel = false;
#ifdef WIN32
	m_threadID = (thread_type)_beginthreadex(NULL, 0,
		&threadFunc, (void*)this, NULL, 0);
#else	
	if (pthread_create(&m_threadID, NULL, threadFunc,
		(void*)this) != 0)
	{
		LogError("createThread error!");
	}
#endif
}
// void Thread::Kill()
// {
// 
// }
void Thread::Cancel()
{
	this->m_isCancel = true;
// #ifdef WIN32
// 	
// #else
// 	pthread_cancel(m_threadID);
// #endif
}
void Thread::Join()
{
#ifdef WIN32
	int i = 0;

	while (true)
	{
		++i;
		DWORD dw = WaitForSingleObject(m_threadID, 3000);

		switch (dw)
		{
		case WAIT_OBJECT_0:
			return;

		case WAIT_TIMEOUT:
			if (i > 20)
			{
				LogError("TPThread::join: can't join thread)");
				return;
			}
			else
			{
				LogWarn("TPThread::join: waiting for thread, try=%d", i);
			}
			break;

		case WAIT_FAILED:
		default:
			LogError("TPThread::join: can't join thread");
			return;
		};
	}
#else
	void* status;
	if (pthread_join(m_threadID, &status))
	{
		LogError("TPThread::join: can't join thread\n");
		return;
	}
#endif

}

